package com.android.takegism.ui;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.android.takegism.R;
import com.android.takegism.service.AdminService;
import com.android.takegism.service.ClientThread;
import com.android.takegism.utils.MyContext;
import com.android.takegism.utils.SensorPackage;
import com.android.takegism.utils.SensorUiItem;
import com.android.takegism.utils.UIHandler;

import java.io.IOException;
import java.io.OutputStream;
import java.util.LinkedList;

public class AdminActivity extends AppCompatActivity implements View.OnClickListener {
    private MyContext myContext = MyContext.getInstance();
    private ImageButton exit_btn;
    private Button test_btn;
    private EditText receive_info;
    private ImageButton go_manage;

    private ClientThread rxListenerThread;//与试验台的连接
    private AdminService server;

    public static Handler mainHandler;
    public static Handler uiHandler;
    public static boolean isConnected;
    public static boolean isServer;

    private ListView listView4SensorUiItem;

    public static Handler messageHandler;

    private static SensorUiItemAdapter sensorUiItemAdapter;
    private Notification.Builder builder;
    private NotificationManager manager;
    private String channelId = "com.android.takagism.ui.AdminActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin);
        init();
    }

    private void init() {
        initMainHandler();
        NotificationChannel channel = new NotificationChannel(channelId, "Channel 23", NotificationManager.IMPORTANCE_DEFAULT);
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.createNotificationChannel(channel);
        builder = new Notification.Builder(this, channel.getId());

        exit_btn = findViewById(R.id.exit_button);
        exit_btn.setOnClickListener(this);
        receive_info = findViewById(R.id.receive_info);
        test_btn = findViewById(R.id.admin_test_btn);
        go_manage = findViewById(R.id.go_manage);
        go_manage.setOnClickListener(this);
        test_btn.setOnClickListener(this);


        //启动服务器
        SensorPackage sensorPackage = new SensorPackage("声音传感器");
        sensorPackage.setDataString("");
        Bundle bundle = new Bundle();
        bundle.putSerializable("sensorPackage", sensorPackage);
        startService(new Intent(this, AdminService.class).putExtras(bundle));

        //连接试验台
        rxListenerThread = new ClientThread(this);
        rxListenerThread.start();

        listView4SensorUiItem = findViewById(R.id.list_sensor);
        LinkedList<SensorUiItem> sensor_data = (LinkedList<SensorUiItem>) MyContext.getInstance().getStatics("sensor_data");
        if (sensor_data == null) {
            sensor_data = new LinkedList<>();
            MyContext.getInstance().setStatics("sensor_data", sensor_data);
        }
        sensorUiItemAdapter = new SensorUiItemAdapter(sensor_data, this);
        listView4SensorUiItem.setAdapter(sensorUiItemAdapter);

        messageHandler = new UIHandler(Looper.myLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                SensorUiItem sensorUiItem = (SensorUiItem) msg.obj;
                // 是否有新增加的
                System.out.println("测试MESSAGE_HANDLER");
                boolean ok = false;
                for (SensorUiItem uiItem : sensorUiItemAdapter.getmData()) {
                    if (uiItem.getType().toString().equals(sensorUiItem.getType().toString())) {
                        uiItem.setData(sensorUiItem.getData());
                        ok = true;
                        sensorUiItemAdapter.changed();
                        break;
                    }
                }
                if (!ok) {
                    sensorUiItemAdapter.add(sensorUiItem);
                }
                System.out.println(sensorUiItemAdapter.getmData());
                super.handleMessage(msg);
            }
        };
        System.out.println(messageHandler);
//        MyContext.getInstance().setStatics("messageHandler", messageHandler);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.exit_button:
                System.out.println("退出");
                finish();
                break;
            case R.id.admin_test_btn:
                startActivity(new Intent(AdminActivity.this, ZzjTestActivity.class));
                break;
            case R.id.go_manage:
                startActivity(new Intent(AdminActivity.this, AdminManageActivity.class));
                break;
            default:
                break;
        }
    }

    private void sendTicker() {

        Intent intent = new Intent(this, AdminActivity.class);
        builder
                .setContentIntent(PendingIntent.getActivity(this, 0, intent, 0))
                .setAutoCancel(true)
                .setTicker("提醒")
                .setContentText("有用户紧急求助！")
                .setContentTitle("SOS")
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setWhen(System.currentTimeMillis())
        ;

        manager.notify((int) System.currentTimeMillis(), builder.build());
    }

    void initMainHandler() {

        uiHandler = new UIHandler(Looper.myLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                // TODO
                super.handleMessage(msg);
            }
        };

        mainHandler = new Handler(Looper.myLooper()) {

            @Override
            /**
             * 主线程消息处理中心
             */
            public void handleMessage(Message msg) {

                // 接收子线程的消息
                switch (msg.what) {
                    case 0x1111:
                        System.out.println("myAdapter.notifyDataSetChanged()");
                        break;
                    case 0x1112:
                        Bundle bundle = msg.getData();
                        byte[] buffer = bundle.getByteArray("sendData");
                        OutputStream outputStream = rxListenerThread.getOutPutStream();
                        try {
                            outputStream.write(buffer);
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        break;
                    case 0x5555:
                        isConnected = true;
                        System.out.println("Toast.makeText(AdminActivity.this, 试验台连接成功！,Toast.LENGTH_LONG).show();");
                        Toast.makeText(AdminActivity.this, "试验台连接成功！", Toast.LENGTH_LONG).show();
                        sendBroadcast(new Intent("com.android.action.nettestfinished"));
                        break;
                    case 0x5556:
                        isConnected = false;
                        System.out.println("Toast.makeText(AdminActivity.this, 试验台连接失败！,Toast.LENGTH_LONG).show();");
                        Toast.makeText(AdminActivity.this, "试验台连接失败！", Toast.LENGTH_LONG).show();
                        sendBroadcast(new Intent("com.android.action.nettestfinished"));
//                        finish();
                        break;
                    case 0x6000:
                        isServer = true;
                        System.out.println("Toast.makeText(AdminActivity.this, 服务器启动成功！,Toast.LENGTH_LONG).show();");
                        Toast.makeText(AdminActivity.this, "服务器启动成功！", Toast.LENGTH_LONG).show();
                        break;
                    case 0x6001:
                        isServer = false;
                        System.out.println("Toast.makeText(AdminActivity.this, 服务器启动失败！,Toast.LENGTH_LONG).show();");
                        Toast.makeText(AdminActivity.this, "服务器启动失败！", Toast.LENGTH_LONG).show();
                        finish();
                        break;
                    case 0x6002:
                        System.out.println("收到信息！");
//                        System.out.println("发送一条数据确定能通信...");
//                        AdminService server = (AdminService) myContext.getStatics("adminService");
//                        if (server==null){
//                            System.out.println("error!未创建");
//                            break;
//                        }
//                        server.sendMessage("YES 我接收了你的连接请求");
                        String str = msg.obj.toString();
                        if (!str.contains("#")) {
                            receive_info.append(str + "\n");
                        } else {//#HELP#
                            @SuppressLint("ShowToast") Toast toast = Toast.makeText(AdminActivity.this, "有用户紧急求助！", Toast.LENGTH_LONG);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            UserMainActivity.showMyToast(toast, 2000);
                            sendTicker();
                        }
                        break;
                    default:
                        break;
                }

            }

        };


    }
}